//
//  AutoScrollView.m
//  AuScrollImage
//
//  Created by mac on 14-9-30.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "AutoScrollView.h"
#import "UIImageView+WebCache.h"
#import "SMPageControl.h"
#import "XLDownloadImageTool.h"
#import "XLTuijianBannnerListModel.h"

#define kInitImgCount 3

// 提示文字字体
#define kTipsTextFont [UIFont boldSystemFontOfSize:16]

@interface AutoScrollView()<UIScrollViewDelegate>
{
    NSInteger _currentPage;
    NSInteger _totalPage;
}

@property (nonatomic, assign) BOOL enableRolling;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIImage *holderImage;
@property (nonatomic, strong) UIView *tipsbg;

@end

@implementation AutoScrollView



- (id)initWithFrame:(CGRect)frame images:(NSArray *)images placeholderImage:(UIImage *)image
{
    self = [self initWithFrame:frame placeholderImage:image andRight:YES];
    if (self) {
        
        // 得到图片名数组
        _images = [[NSArray alloc] initWithArray:images];
        // 设置总页数和当前第几页
        _totalPage = images.count;
        
        _pageControl.numberOfPages = images.count;
        _pageControl.pageIndicatorTintColor = [UIColor grayColor];
        [self refreshScrollView];
        
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame placeholderImage:(UIImage *)image andRight:(BOOL)isRight
{
    self = [super initWithFrame:frame];
    if (self) {
        // 得到图片名数组
        _images = [NSArray array];
        _holderImage = image;
        // 设置总页数和当前第几页
        _totalPage = kInitImgCount;
        _currentPage = 1;
        
        // 1.初始化scrollview
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        CGFloat width = self.bounds.size.width;
        CGFloat height = self.bounds.size.height;
        scrollView.frame = CGRectMake(0, 0, width, height);
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.delegate = self;
        scrollView.scrollsToTop = NO;
        // 2.添加scrollView
        [self addSubview:scrollView];
        scrollView.contentSize = CGSizeMake(width * kInitImgCount, 0);
        _scrollView = scrollView;
        
        // 3.往scrollView上添加图片
        for (int i = 0; i<kInitImgCount; i++) {
            UIImageView *imgView = [[UIImageView alloc] init];
            imgView.image = [UIImage imageNamed:@"默认商品图正方形.png"];
            ViewRadius(imgView, 4);
            imgView.clipsToBounds = YES;
            imgView.contentMode = UIViewContentModeScaleAspectFit;
            imgView.frame = CGRectMake(i*width, 0, width, height);
            [scrollView addSubview:imgView];
            // 设置imgview上的图片
            //[imgView setImage:image];
            
            // 添加单击事件
            imgView.userInteractionEnabled = YES;
            [imgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]];
        }
        
        // 4.提示文字背景
        UIView *tipsbg = [[UIView alloc] init];
        [self addSubview:tipsbg];
        tipsbg.backgroundColor = [UIColor blueColor];
        tipsbg.frame = CGRectMake(0, height - 28, width, 28);
        tipsbg.hidden = YES;
        _tipsbg = tipsbg;
        
        // 5.添加页标
        SMPageControl *pageControl = [[SMPageControl alloc] init];
        [self addSubview:pageControl];
        pageControl.frame = CGRectMake(self.bounds.size.width-5-120, self.bounds.size.height-15, 120, 15);
        pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        pageControl.numberOfPages = kInitImgCount;
        pageControl.currentPage = 0;
        pageControl.indicatorMargin = 8;
        pageControl.indicatorDiameter = 8;
        pageControl.alignment = SMPageControlAlignmentRight;
        pageControl.hidden = YES;
        pageControl.hidesForSinglePage = YES;
        _pageControl = pageControl;
        
        // 6.添加label
        UILabel *label = [[UILabel alloc] init];
        [tipsbg addSubview:label];
        label.font = kTipsTextFont;
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.frame = CGRectMake(5, 0, width-5-pageControl.frame.size.width, tipsbg.frame.size.height);
        label.text = @"";
        _label = label;
        //是在中间并且隐藏位置
        if( !isRight ){
            _tipsbg.backgroundColor = [UIColor clearColor];
            _label.hidden = YES;
            _pageControl.frame = CGRectMake((self.bounds.size.width-120)/2.0, self.bounds.size.height-15, 120, 15);
            _pageControl.alignment = SMPageControlAlignmentCenter;
        }
    }
    return self;
}

#pragma mark 设置数据
- (void)setImages:(NSArray *)images
{
    // 显示提示
    _tipsbg.hidden = NO;
    _pageControl.hidden = NO;
    _scrollView.scrollEnabled = YES;
    if (images.count > 0) {
        [self reloadWithData:images];
        [self refreshScrollView];
        if (images.count == 1) {
            _pageControl.hidden = YES;
            _scrollView.scrollEnabled = NO;
            [self stopRolling];
        }
    }
}

#pragma mark 重新设置数据
- (void)reloadWithData:(NSArray *)images
{
    if (self.enableRolling)
    {
        [self stopRolling];
    }
    
    _images = images;
    _totalPage = images.count;
    _currentPage = 1;
    _pageControl.numberOfPages = _totalPage;
    _pageControl.currentPage = 0;
    
}

#pragma mark 单击一张图片
- (void)handleTap:(UITapGestureRecognizer *)tap
{
    if ([_delegate respondsToSelector:@selector(autoScrollView:didSelectImageIndex:)]) {
        [_delegate autoScrollView:self didSelectImageIndex:_currentPage-1];
    }
}

#pragma mark ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat x = scrollView.contentOffset.x;
    // 取消加入的延时线程
    if (_enableRolling)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
    }
    
    // 往后翻
    if (x >= 2*_scrollView.frame.size.width) {
        _currentPage = [self getPageIndex:_currentPage + 1];

        // 刷新scrollView
        [self refreshScrollView];
    }
    else if( x <= 0 )
    { // 往前翻
        _currentPage = [self getPageIndex:_currentPage - 1];
        [self refreshScrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    _scrollView.contentOffset = CGPointMake(_scrollView.frame.size.width, 0);
    
    // 自动滚动
    if (_enableRolling)
    {
        [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:_rollingDelayTime];
    }
}

#pragma mark 更新文字
- (void)refreshLabelText
{
    XLTuijianBannnerListModel *imageData = _images[_currentPage-1];
    _label.text = @"";
}

#pragma mark 开始自动滚动
- (void)startRolling
{
    if ([_images count] <= 1) {
        return;
    }
    
    [self stopRolling];
    _enableRolling = YES;
    [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:_rollingDelayTime];
}

#pragma mark 停止自动滚动
- (void)stopRolling
{
    _enableRolling = NO;
    //取消已加入的延迟线程
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
}

#pragma mark 执行滚动动画并继续延时递归调用
- (void)rollingScrollAction
{
    [UIView animateWithDuration:0.25 animations:^{
        _scrollView.contentOffset = CGPointMake(1.99*_scrollView.frame.size.width, 0);
    } completion:^(BOOL finished) {
        _currentPage = [self getPageIndex:_currentPage+1];
        [self refreshScrollView];
        
        if (_enableRolling) {
            [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:_rollingDelayTime];
        }
    }];
}

#pragma mark 得到下个正确页数
- (NSInteger)getPageIndex:(NSInteger)index
{
    NSInteger ret = index;
    if (index == 0) { // 往前翻到最后一页
        ret = _totalPage;
    }else if( index == _totalPage + 1){ // 往后翻到第一页
        ret = 1;
    }
    
    return ret;
}

#pragma mark 刷新scrollView
- (void)refreshScrollView
{
    NSArray *currentImageUrls = [self getDisplayImagesWithPageIndex:_currentPage];
    for (NSInteger i = 0; i < kInitImgCount; i++)
    {
        UIImageView *imageView = (UIImageView *)(_scrollView.subviews[i]);
        XLTuijianBannnerListModel *imageData = currentImageUrls[i];
        NSString *url = imageData.Img;
        if (imageView && [imageView isKindOfClass:[UIImageView class]] && url)
        {
            // 刷新图片
            [XLDownloadImageTool downloadImage:url place:_holderImage imageView:imageView];
            
        }
    }
    
    _scrollView.contentOffset = CGPointMake(_scrollView.frame.size.width, 0);
    _pageControl.currentPage = _currentPage - 1;
    //更新sound中文字
    if ([_delegate respondsToSelector:@selector(autoScrollView:didScrollToImageData:)]) {
        [_delegate autoScrollView:self didScrollToImageData:_images[_currentPage-1]];
    }
    // 更新文字
    [self refreshLabelText];
}

#pragma mark 得到最新的图片展示数组
- (NSArray *)getDisplayImagesWithPageIndex:(NSInteger)page
{
    NSInteger pre = [self getPageIndex:_currentPage-1];
    NSInteger next = [self getPageIndex:_currentPage+1];
    
    NSMutableArray *images = [NSMutableArray array];
    [images addObject:[_images objectAtIndex:pre-1]];
    [images addObject:[_images objectAtIndex:_currentPage-1]];
    [images addObject:[_images objectAtIndex:next-1]];
    
    return images;
}

#pragma mark 析构
- (void)dealloc
{
    // 取消所有延时
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
}
@end
